package com.baomidou.mybatisplus.generator;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.GlobalConfig;
import com.baomidou.mybatisplus.generator.config.PackageConfig;
import com.baomidou.mybatisplus.generator.config.StrategyConfig;
import com.baomidou.mybatisplus.generator.config.rules.DateType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import com.baomidou.mybatisplus.generator.util.ColumnTable;
import com.baomidou.mybatisplus.generator.util.Util;

public class Main {

	public static void main(String[] args) throws Exception {
		SAXReader reader = new SAXReader();
		Document document = null;
		if (args.length != 0) {
			document = reader.read(new File(args[0]));
		} else {
			document = reader.read(new File("src/main/resources/codeGenerator.xml"));
		}
		Element root = document.getRootElement();
		// 获取dataSource节点
		Element dataSource = root.element("dataSource");
		// 获取globalConfig节点
		Element globalConfig = root.element("globalConfig");
		// 获取packageConfig节点
		Element packageConfig = root.element("packageConfig");
		// 获取tableConfig节点
		Element tableConfig = root.element("tableConfig");
		// 获取table节点的迭代
		@SuppressWarnings("unchecked")
		Iterator<Element> it = root.elementIterator("table");

		// 代码生成器
		AutoGenerator mpg = new AutoGenerator();

		// 全局配置
		GlobalConfig gc = new GlobalConfig();
		if (Util.isNotEmpty(globalConfig.elementText("outDir"))) {
			gc.setOutputDir(globalConfig.elementText("outDir"));
		}
		if (Util.isNotEmpty(globalConfig.elementText("open"))) {
			gc.setOpen(Boolean.parseBoolean(globalConfig.elementText("open")));
		}
		if (Util.isNotEmpty(globalConfig.elementText("author"))) {
			gc.setAuthor(globalConfig.elementText("author"));
		}
		if (Util.isNotEmpty(globalConfig.elementText("swagger2"))) {
			gc.setSwagger2(Boolean.valueOf(globalConfig.elementText("swagger2")));
		}
		if (Util.isNotEmpty(globalConfig.elementText("baseResultMap"))) {
			gc.setBaseResultMap(Boolean.valueOf(globalConfig.elementText("baseResultMap")));
		}
		if (Util.isNotEmpty(globalConfig.elementText("dateJDK8"))) {
			Boolean date = Boolean.valueOf(globalConfig.elementText("dateJDK18"));
			if (date) {
				gc.setDateType(DateType.TIME_PACK);
			} else {
				gc.setDateType(DateType.ONLY_DATE);
			}
		}
		if (Util.isNotEmpty(globalConfig.elementText("stringId"))) {
			gc.setStringId(Boolean.valueOf(globalConfig.elementText("stringId")));
		}
		gc.setFileOverride(true);
		mpg.setGlobalConfig(gc);

		// 数据源
		DataSourceConfig dsc = new DataSourceConfig();
		dsc.setDbType(DbType.MYSQL);
		dsc.setUrl(dataSource.elementText("url"));
		dsc.setDriverName(dataSource.elementText("driverClassName"));
		dsc.setUsername(dataSource.elementText("username"));
		dsc.setPassword(dataSource.elementText("password"));
		mpg.setDataSource(dsc);

		// 包配置
		PackageConfig pc = new PackageConfig();
		if (Util.isNotEmpty(packageConfig.elementText("parent"))) {
			pc.setParent(packageConfig.elementText("parent"));
		}
		if(Util.isNotEmpty(packageConfig.elementText("controllerPackage"))) {
			pc.setController(packageConfig.elementText("controllerPackage"));
			pc.setControllerPackage(packageConfig.elementText("controllerPackage"));
		}
		mpg.setPackageInfo(pc);
		// 数据库表配置
		StrategyConfig strategy = new StrategyConfig();
		// <table>节点表集合
		List<String> tableNames = new ArrayList<>();
		/** 需要生成的表 */
		while (it.hasNext()) {
			Element table = it.next();
			String tableName = table.attributeValue("name");
			tableNames.add(tableName);
		}
		if (Util.isNotEmpty(tableConfig.elementText("include"))) {
			//include的节点不为空
			String[] strs = tableConfig.elementText("include").split(",");
			List<String> all = new ArrayList<String>(Arrays.asList(strs));
			if (!tableNames.isEmpty()) {
				all.addAll(tableNames);
			}
			strategy.setInclude(all.toArray(new String[all.size()]));
		}else {
			//include节点为空
			strategy.setExclude("");
		}

		// 有typeHandler的表
		List<ColumnTable> handlerTable = Util.getTypeHandlerTable(root);
		if (!handlerTable.isEmpty()) {
			strategy.setColumnTableList(handlerTable);
		}

		/** 表前缀 */
		if (Util.isNotEmpty(tableConfig.elementText("tablePrefix"))) {
			strategy.setTablePrefix(tableConfig.elementText("tablePrefix") + "_");
		}
		/** restController */
		if (Util.isNotEmpty(tableConfig.elementText("restControllerStyle"))) {
			strategy.setRestControllerStyle(Boolean.valueOf(tableConfig.elementText("restControllerStyle")));
		}
		/** lombok */
		if (Util.isNotEmpty(tableConfig.elementText("lombokModel"))) {
			strategy.setEntityLombokModel(Boolean.valueOf(tableConfig.elementText("lombokModel")));
		}

		strategy.setNaming(NamingStrategy.underline_to_camel);
		mpg.setStrategy(strategy);
		// 使用freemarker引擎
		mpg.setTemplateEngine(new FreemarkerTemplateEngine());
		mpg.execute();
	}
}
